package com.qiche.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.qiche.config.YmlConfig;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
* JsonRpcUtils : jsonrpc工具类
*
* @author zhangds
* @since 2017-05-03 15:05
*/
public class JsonRpcUtils {

    @Autowired
    private static  YmlConfig ymlConfig;
   public static String getResult(String phone,String openid,String mac){
       String result = "";
       try {
           JsonRpcHttpClient client = new JsonRpcHttpClient(new URL(ymlConfig.getWifiApiUrl()));
           Map<String, String> paras = new HashMap<String, String>();
           paras.put("sign", "YHL");
           paras.put("phone", phone);
           paras.put("openid", openid);
           paras.put("mac", mac);
           Object rt = client.invoke("getUserPhone", paras, Object.class);
           result = new Gson().toJson(rt);
       } catch (MalformedURLException e) {
           e.printStackTrace();
       } catch (Throwable throwable) {
           throwable.printStackTrace();
       }
       return result;
   }

    public static boolean isConnectWifiByOpenId(String openid) {
        Gson gson = new Gson();
        String result = getResult("", openid, "");
        if (result == null || "".equals(result) || "null".equals(result) || "\\[\\]".equals(result)) {
            return false;
        }
        JsonObject wifi_userinfo = new JsonObject();
        JsonArray wifi_userinfos = gson.fromJson(result, JsonArray.class);// 把字符串转换为json对象
        for (JsonElement jsonElement : wifi_userinfos) {
            wifi_userinfo = jsonElement.getAsJsonObject();
            if ("online".equals(wifi_userinfo.get("status").getAsString())) {
                return true;
            }
        }
        return false;
    }

    public static boolean isConnectWifiByPhone(String phone) {
        Gson gson = new Gson();
        String result = getResult(phone, null, null);
        if (result == null || "".equals(result) || "null".equals(result) || "\\[\\]".equals(result)) {
            return false;
        }
        JsonObject wifi_userinfo = new JsonObject();
        JsonArray wifi_userinfos = gson.fromJson(result, JsonArray.class);// 把字符串转换为json对象
        for (JsonElement jsonElement : wifi_userinfos) {
            wifi_userinfo = jsonElement.getAsJsonObject();
            if ("online".equals(wifi_userinfo.get("status").getAsString())) {
                return true;
            }
        }
        return false;
    }

   public static void main(String[] args){
       boolean falh=  isConnectWifiByPhone("15989356973");
       System.out.println("65666666666:"+falh);
   }


}
